<template>
  <!-- 一二三级分类全局组件 -->
  <Category :isDisabled="isDisabled"></Category>

  <!-- 卡片 -->
  <el-card style="margin-top: 15px;" shadow="hover">
    <!-- 场景1 -->
    <div v-show="isActive == 0">
      <el-button type="primary" :icon="Plus" @click="goSpu" :disabled="useCategory.c3Id ? false : true">添加SPU</el-button>
      <!-- 表格 -->
      <el-table border style="margin-top: 20px;" :data="spuArr">
        <el-table-column label="序号" type="index" width="85px"></el-table-column>
        <el-table-column label="SPU名称" prop="spuName"></el-table-column>
        <el-table-column label="SPU描述" prop="description" show-overflow-tooltip></el-table-column>
        <el-table-column label="SPU操作">
          <template #="{ row, $index }">
            <el-button title="添加SKU" :icon="Plus" type="primary" @click="addSku(row)"></el-button>
            <el-button title="修改SPU" :icon="Edit" type="warning" @click="getSpuAll1(row)"></el-button>
            <el-button title="查看SKU" :icon="InfoFilled" type="info" @click="ShowSkuList(row, $index)"></el-button>
            <el-button title="删除SPU" :icon="Delete" type="danger" @click='deleteSpu(row.id)'></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination style="margin-top: 15px;" v-model:current-page="page" v-model:page-size="pageSize" small background
        layout=", prev, pager, next,, jumper,->,sizes,total " :total="total" :page-sizes="[3, 5, 7, 9]" class="mt-4"
        @current-change="changePageNo" @size-change="changeSize" />
    </div>

    <!-- dialog谈话框 用于展示一个spu的列表 -->
    <el-dialog v-model="visible">
      <template #header="{ close, titleId, titleClass }" #="{row,$index}">
        <el-button type="info" style="margin-bottom: 12px;">SKU列表</el-button>
        <el-table border :data="SkuList">
          <el-table-column label="SKU名称" prop="skuName"></el-table-column>
          <el-table-column label="SKU价格" prop="price"></el-table-column>
          <el-table-column label="SKU重量" prop="weight"></el-table-column>
          <el-table-column label="SKU图片">
            <template #="{ row, $index }">
              <img :src="row.skuDefaultImg" style="width: 120px;height: 110px;">
            </template>
          </el-table-column>
        </el-table>
      </template>

    </el-dialog>





    <!-- 场景2 修改SPU-->
    <div v-show="isActive == 1">
      <el-form>
        <!-- input框 -->
        <el-form-item label="SPU名称">
          <el-input placeholder="请你输入SPU名称" v-model="spuParams.spuName" />
        </el-form-item>
        <!-- 下拉框 -->
        <el-form-item label="SPU品牌">
          <el-select placeholder="请选择" v-model="spuParams.tmId">
            <el-option v-for="spu in sputrademarkarr" :key="spu.id" :label="spu.tmName" :value="spu.id" />
          </el-select>
        </el-form-item>
        <!-- 输入文本框 -->
        <el-form-item label="SPU描述">
          <el-input type="textarea" v-model="spuParams.description" />
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="SPU图片">
          <el-upload v-model:file-list="imgList" action="/api/admin/product/upload" list-type="picture-card" drag
            :before-upload="BeforeUPload" :on-exceed="OnExceed" :on-success="handleAvatarSuccess" :limit="13">
            <el-icon>
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>
        <!-- 销售属性 -->
        <el-form-item label="SPU销售属性" inline>
          <el-select placeholder="请选择" v-model="SPUregion">
            <el-option v-for="item in unSale" :key="item.id" :value="`${item.id}:${item.name}`" :label="item.name" />
          </el-select>
          <el-button style="margin-left: 10px;" type="primary" :icon="Plus" :disabled="!!!unSale"
            @click="addAttr">添加销售属性</el-button>
        </el-form-item>
        <!-- 表格 -->
        <el-table border style="margin-bottom: 15px;" :data="saleArr">
          <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
                :type="tag.type" @close="deleteAttrValue($index, index)">
                {{ tag.saleAttrValueName }}
              </el-tag>

              <el-input style="width: 70px;" size="small" @blur="inputBlur(row, $index)" ref="input" v-if="row.senced"
                v-model="inputVal"></el-input>
              <el-button type="success" size="small" icon="ele-Plus" v-else
                @click="changeButton(row, $index)"></el-button>


            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button :icon="Delete" type="danger"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="updateAtrrValue">保存</el-button>
        <el-button type="info" @click="isActive = 0">取消</el-button>
      </el-form>
    </div>

    <!-- 场景3 添加SKU-->
    <Form v-show="isActive == 2" @sence="sence" ref="SKU"></Form>

  </el-card>
</template>

<script setup lang="ts">
import Form from './form/index.vue'
import { ElMessage } from 'element-plus';
import { ref, watch, onMounted, reactive, computed } from 'vue';
// 引入element-plls-icon图标 
import { Plus, UploadFilled, Edit, More, Delete, InfoFilled } from '@element-plus/icons-vue';
// 引入api发请求函数
import { reqSpuData, reqSpuTrademarkList, reqSpuBaseAttr, reqDeleteSpu, reqSupImgList, reqAllSpuAttr, reqAddOrUpdateSpu, reqSkuList } from '@/api/product/spu/index'
// 引入ts定义类型
import type { Records, Record, SpuResponeData, SpuTrademarkList, SpuSpuTrademarkArr, SpuBaseAttrList, SpuBaseAttr, ImageTypeArr, SpuAttr, SkuArr } from '@/api/product/spu/types/index'
import UseCategoryStore from '@/stores/category'
import { nextTick } from 'vue';
import type { UploadProps } from 'element-plus'
// 调用小仓库
const useCategory = UseCategoryStore()
// 定义切换与隐藏的按钮
let isActive = ref<any>(0)
// 禁用分类的选框
let isDisabled = ref(false)
// 当前在第几页
let page = ref(1)
// 一页几条数据
let pageSize = ref(3)
// 总数
let total = ref(30)
// 获取input的dom元素
let input = ref()
// 
let inputVal = ref('')
// 存放数据的数组
let spuArr = ref<Records>([])
// 存放SPU品牌数据
let sputrademarkarr = ref<SpuSpuTrademarkArr>([])
// 存放SPU销售属性
let spubaselist = ref<SpuBaseAttrList>([])
// -------------------------------------------------------------------------
// 获取ref实例
let SKU = ref()
//存储还未选择销售属性的ID与名字
const saleIdAndValueName = ref<string>('');


// 收集SPU名称的内容
let inputValue = ref('')
// 收集SPU描述的内容
let description = ref('')
// 收集SPU品牌的内容
let region = ref('')
// 收集SPU销售属性的内容
let SPUregion = ref('')
// 控制属性值按钮和input
let senced = ref(true)
// 场景3收集数据-----------
let ruleForm = ref({
  regionm: ''
})
// ----------------------------------------------------------------------------------
// 存放全部品牌的数据
let allTrademark = ref<any>([])
//存放已有的销售属性
let saleArr = ref<any>([])
// 存放照片墙的数据
let imgArr = ref<any>([])
// 存放照片的格式
let imgList = ref<any>([])
// 存放全部的销售属性
let allSaleArr = ref<any>([])
// 存储已有的SPU
let spuParams = reactive<any>({
  id: '',
  spuName: '',
  description: '',
  tmId: undefined,
  category3Id: '',
  spuSaleAttrList: [],
  spuImageList: []
})

// 控制dialog框的显示与隐藏
const visible = ref(false)
// 存放SKU列表
let SkuList = ref<SkuArr>([])

// 给子组件绑定自定义事件
let sence = (active: number) => {
  // 儿子通知die来切换场景
  isActive.value = active
}

// 发请求获取数据
let getSpudata = async () => {
  // 发请求袖带page和pagesize和三级分类的id等参数
  let res: SpuResponeData = await reqSpuData(page.value, pageSize.value, useCategory.c3Id)
  // 将数据一一替换
  total.value = res.total
  page.value = res.current
  pageSize.value = res.size
  spuArr.value = res.records
  // console.log(res)
}

// 监视三级分类的变化
watch(() => useCategory.c3Id, () => {
  // 发生变化发请求
  useCategory.c3Id && getSpudata()
})

// 当pigeSize发生改变调用该函数
let changePageNo = () => {
  // 发请求获取最新数据
  getSpudata()
}

// 当分页数改变改变时调用函数发请求获取新数据
let changeSize = () => {
  getSpudata()
}

// 发请求获取SPU品牌的数据
let getSpuTardemark = async () => {
  let result: SpuTrademarkList = await reqSpuTrademarkList()
  sputrademarkarr.value = result
  // console.log(result)
}

let getspubase = async () => {
  // 发请求获取全部销售属性 
  let result: SpuBaseAttr[] = await reqAllSpuAttr()
  // 赋值给响应式数据
  // console.log(spubaselist.value);
  // console.log(result);


  spubaselist.value = result
  // console.log(result)
}

//新增SPU按钮的回调
let goSpu = async () => {
  // 在点击添加spu的按钮之前,把之前的数据清空
  ResetSpu()
  // 切换场景
  isActive.value = 1
  spuParams.category3Id = useCategory.c3Id
  // 获取全部的销售属性
  getspubase()
  // 获取全部品牌
  getSpuTardemark()

}

// 清空spu数据的函数
let ResetSpu = () => {
  Object.assign(spuParams, {
    id: '',
    spuName: '',
    description: '',
    tmId: undefined,
    category3Id: '',
    spuSaleAttrList: [],
    spuImageList: []
  })
  // 照片墙等于空数组
  imgList.value = []
  // 销售属性等于空数组
  saleArr.value = []
}

// 添加sku的回调
let addSku = (row: any) => {

  // 切换到添加页面
  isActive.value = 2
  // 禁用分类的下拉框
  isDisabled.value = true
  SKU.value.initSKu(row)
}

// 点击修改SPU的回调
let getSpuAll1 = async (row: Record) => {
  console.log(row);

  // 分类选框切换场景禁用
  isDisabled.value = true
  // console.log(row);
  // 合并对象
  spuParams.category3Id = row.category3Id
  spuParams.id = row.id
  spuParams.spuName = row.spuName
  spuParams.description = row.description
  spuParams.tmId = row.tmId
  spuParams.spuImageList = imgArr.value
  // Object.assign(spuParams, row)
  spuParams.spuImageList = []
  // 获取全部品牌
  getSpuTardemark()
  //获取全部属性
  getspubase()
  // 将场景切换为1
  isActive.value = 1
  // 获取照片墙的数据
  let result1: ImageTypeArr = await reqSupImgList(row.id as any)
  console.log(result1);
  imgArr.value = []
  imgArr.value = result1
  //  console.log(result1)
  const imglist = result1.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
  imgList.value = imglist
  // 获取全部销售属性
  // let result2 =  await reqAllSpuAttr()
  // allSaleArr.value = result2 
  // 获取某一个的销售属性
  let result3 = await reqSpuBaseAttr(row.id as any)

  saleArr.value = result3





}

// 计算属性:计算出未展示的销售属性
const unSale = computed(() => {
  return spubaselist.value.filter((item) => {
    return saleArr.value.every((item1: SpuAttr) => {
      return item.name != item1.saleAttrName.trim()
    })
  })
})

// 图片上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  if (response.data) {
    spuParams.spuImageList.push({
      imgName: uploadFile.name,
      imgUrl: response.data
    })
  }
}

// 图片上传前对图片的限制
let BeforeUPload = (file: any) => {
  // 对图片进行类型限制
  if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif') {
    // 对图片进行大小限制
    if (file.size / 1024 / 1024 < 2) {
      ElMessage({
        type: 'success',
        message: '图片上传成功！！'
      })
      return true;
    }
  } else {
    // 消息提示
    ElMessage({
      type: 'error',
      message: '上传图片格式不正确！'
    })
    return false;
  }
}

// 当图片超出限制时的钩子
let OnExceed = () => {
  ElMessage({
    type: "warning",
    message: '最多可上传四张图片！！'
  })
}

// 添加新的销售属性的钩子
let addAttr = () => {
  // console.log(SPUregion.value)
  //存储的还未有销售是属性ID与名字切割出来
  const [baseSaleAttrId, saleAttrName] = SPUregion.value.split(':');
  //向已有的销售属性的数组追加新的对象
  const newSaleAttr: any = {
    inputValue: spuParams.id,
    baseSaleAttrId,//新增销售属性的ID
    saleAttrName,//新增销售属性的名字
    spuSaleAttrValueList: [],//销售是属性值的数组
    senced: false
  }

  saleArr.value.push(newSaleAttr);
  // 清空收集销售属性字符串
  SPUregion.value = '';
}

// 添加属性值的回调
let changeButton = (row: any, index: number) => {
  // 点击button按钮切换到input
  saleArr.value[index].senced = true
  nextTick(() => {
    // 获取最新的dom元素,聚焦到input框中
    input.value.focus()
  })
}

// input失去焦点的回调
let inputBlur = (row: any, index: number) => {
  console.log(row);


  // 添加属性值
  let NewSaleAttrValue = {
    spuId: row.spuId,
    // 属性值所需要的id
    baseSaleAttrId: row.baseSaleAttrId,
    // 属性值所需要的名字
    saleAttrValueName: inputVal.value,
    saleAttrName: row.saleAttrName
  }



  // 属性值不能重复
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return inputVal.value == item.saleAttrValueName
  })
  // console.log(repeat)
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return
  }

  row.spuSaleAttrValueList.push(NewSaleAttrValue)
  // input失去焦点切换到button
  saleArr.value[index].senced = false
  // 把input框的内容置为空
  inputVal.value = ''

}

// 删除属性值的回调
let deleteAttrValue = (index: number, i: number) => {
  // 从下标开始删除,删除1个
  saleArr.value[index].spuSaleAttrValueList.splice(i, 1)
}

// 点击保存上传的回调
let updateAtrrValue = async () => {
  console.log(spuParams);

  // 收集参数：属性值数组的内容
  spuParams.spuSaleAttrList = saleArr.value
  // 收集参数：图片数组的内容
  if (imgArr.value) {
    console.log(111);
    spuParams.spuImageList.push(...imgArr.value)
  }
  console.log(spuParams.spuImageList);
  console.log(spuParams);
  // // 发请求修改spu
  await reqAddOrUpdateSpu(spuParams)
  ElMessage({
    // 提示消息
    type: 'success',
    message: '操作成功!!'
  })
  // console.log(spuParams);
  // 发请求获取最新数据
  getSpudata()
  // 切换场景
  isActive.value = 0
}

//查看SKU列表的回调
let ShowSkuList = async (row: any, index: number) => {
  // 点击dialog展示
  visible.value = true
  // 发请求获取某一个spu下所有的sku
  let result = await reqSkuList(row.id)
  SkuList.value = result
  console.log(result)
}






// 删除SPU的回调
let deleteSpu = async (id: number) => {
  // 根据SPU的id来删除对应的spu
  // console.log(id)
  await reqDeleteSpu(id).then(() => {
    ElMessage({
      type: 'success',
      message: "删除成功！！"
    })
    // 发请求获取最新数据
    getSpudata()
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  })
}



</script>
<script lang="ts">
export default {
  name: 'Spu'
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.mx-1 {
  margin-left: 5px
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>